package com.xjh.him.activity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.xjh.him.R;
import com.xjh.him.adapter.TrendPublishAdapter;
import com.xjh.him.core.BaseActivity;
import com.xjh.him.databinding.ActivityTrendPublishBinding;
import com.xjh.him.dto.trend.TrendPublishDTO;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.actionbar.TitleUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class TrendPublishActivity extends BaseActivity<ActivityTrendPublishBinding> {
    private TrendPublishAdapter mAdapter;

    @Override
    protected ActivityTrendPublishBinding viewBindingInflate(LayoutInflater inflater) {
        return ActivityTrendPublishBinding.inflate(inflater);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initTitle();
        initViews();
        initListeners();
    }

    private void initListeners() {

    }

    private void initViews() {
        GridLayoutManager manager = new GridLayoutManager(this, 4, RecyclerView.VERTICAL, false);
        binding.rvImgList.setLayoutManager(manager);
        mAdapter = new TrendPublishAdapter(this);
        binding.rvImgList.setAdapter(mAdapter);
    }

    private void initTitle() {
        TitleBar titleBar = TitleUtils.addTitleBarDynamic(binding.getRoot(), "", v -> {
            hideCurrentPageSoftInput();
            popPage();
        });
        titleBar.addAction(new TitleBar.TextAction("发布") {
            @Override
            public void performAction(View view) {
                hideCurrentPageSoftInput();

                new Thread(() -> {
                    List<String> imgUrlList = uploadImages();
                    publishTrend(imgUrlList);
                }).start();

                popPage();
            }
        });
    }

    private List<String> uploadImages() {
        List<String> imgUrlList = new ArrayList<>();
        List<String> pathList = mAdapter.getPathList();
        if (pathList.size() == 0) {
            return imgUrlList;
        }

        CountDownLatch latch = new CountDownLatch(pathList.size());
        String uploadUrl = Utils.getSevServerApiUrl(TrendPublishActivity.this, getString(R.string.api_img_upload));
        for (String path : pathList) {
            SimpleCallBack<String> uploadCB = new SimpleCallBack<String>() {
                @Override
                public void onSuccess(String response) throws Throwable {
                    imgUrlList.add(response);
                    latch.countDown();
                }

                @Override
                public void onError(ApiException e) {
                    XToastUtils.error(e.getDisplayMessage());
                    latch.countDown();
                }
            };
            Utils.uploadFile(uploadUrl, new File(path), uploadCB);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return imgUrlList;
    }

    private void publishTrend(List<String> imgUrlList) {
        String publishUrl = Utils.getWebServerApiUrl(TrendPublishActivity.this, getString(R.string.api_trend_publish));
        TrendPublishDTO publishDTO = new TrendPublishDTO();
        publishDTO.setTextContent(binding.etTextContent.getText().toString());
        publishDTO.setImgUrlList(imgUrlList);
        SimpleCallBack<Boolean> publishCB = new SimpleCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean response) throws Throwable {
                runOnUiThread(() -> {
                    TrendActivity.refreshTrendList(TrendPublishActivity.this);
                });
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.error(e.getDisplayMessage());
            }
        };
        Utils.doPost(publishUrl, JSON.toJSONString(publishDTO), publishCB);
    }
}
